package org.domain.sigepac.validator;

import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Name("validadorData")
@BypassInterceptors
@org.jboss.seam.annotations.faces.Validator
public class ValidadorData implements Validator {

  
  public void validate(FacesContext context, UIComponent component, Object value)
      throws ValidatorException {

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");

    try {
      String menor = "01/01/1753";
      String maior = "31/12/9999";

      Date menorDataPossivel = simpleDateFormat.parse(menor);
      Date maiorDataPossivel = simpleDateFormat.parse(maior);
      Date data = (Date) value;

      if (data.before(menorDataPossivel)
          || data.after(maiorDataPossivel)) {

        throw new ValidatorException(new FacesMessage(
            FacesMessage.SEVERITY_ERROR,
            String.format("Informe uma data entre %s e %s", menor, maior),
            null)
        );
      }

    } catch (ParseException e) {
      throw new ValidatorException(new FacesMessage(
          FacesMessage.SEVERITY_ERROR, "Data inv\u00e1lida", e.getMessage())
      );
    }

  }

}
